package com.project.modules.quartz;

import com.project.common.service.RedisService;
import com.project.modules.netty.WebSocketHandler;
import com.project.security.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import static com.project.modules.redEnvelope.constant.Constant.RED_ENVELOPE_DURING_SECONDS;
import static com.project.modules.redEnvelope.constant.Constant.RED_ENVELOPE_LOCK;

@Slf4j
public class StartJob extends QuartzJobBean {
    // 如果在这个类里面去@Autowire某些JavaBean，是注入不进去的。Job 对象实例化的过程是通过 Quartz 内部自己完成的。
//    @Autowired
//    private RedisService redisService;

    @Autowired
    private Scheduler scheduler;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        Trigger trigger = context.getTrigger();
        JobDetail jobDetail = context.getJobDetail();
        // 将添加任务的时候存进去的数据拿出来
        Long redId = context.getJobDetail().getJobDataMap().getLong("redId");
        // 编写任务的逻辑：根据红包id加锁
        RedisService redisService = SpringUtil.getBean(RedisService.class);
        redisService.acquireLock(RED_ENVELOPE_LOCK + redId, RED_ENVELOPE_DURING_SECONDS * 2);
        log.info("通知用户开始红包雨" + redId);
        WebSocketHandler.sendMessage(redId, "@order###red-envelope-start");
        // 执行之后删除任务
        try {
            // 暂停触发器的计时
            scheduler.pauseTrigger(trigger.getKey());
            // 移除触发器中的任务
            scheduler.unscheduleJob(trigger.getKey());
            // 删除任务
            scheduler.deleteJob(jobDetail.getKey());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
